<template>
	<view class="box">
		<view class="row">
			<text>手机号</text>
			<input type="text" v-model="phone" maxlength="12"/>
		</view>
		<view class="row">
			<view class="send">
				<!-- :disable 要不要禁用 -->
				<button @click="sendCode" :disabled="!codeTag" class="captcha" type="primary" size="mini">验证码</button>
				<text>{{second}}</text>
			</view>
			<input type="text" v-model="code"  placeholder="- - - -" maxlength="4" />
		</view>
		<view class="row">
			<text style="font-size: 23rpx;">收不到验证码？试试 <text style="color:#00BB00;font-size: 23rpx;"> 语音验证</text></text>
			<!--   -->
			<button @click="login" :disabled="!loginTag" type="primary" style="width: 90%;border-radius: 80rpx;margin-top: 50rpx;">登录</button>
		</view>
		<view class="row">
			<text style="color: #006699;text-align: center;" >通过微信授权登录</text>
		</view>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				phone:'',
				code:'',
				codeTag:false,
				loginTag:false,
				second:''
			}
		},
		watch:{
			//验证电话号码
			phone:function(val){
				var result = /^1[34565789]\d{9}$/.test(val)
				if(result){
					this.codeTag=true;
				}else{
					this.codeTag=false;
				}
			},
			//验证码是否正确
			code:function(val){
				if(val.length==4 && this.codeTag){
					this.loginTag=true;
				}else{
					this.loginTag=false;
				}
			}
		},
		methods:{
			//获取验证码，同时将验证码存储在本地缓存中
			async sendCode(){
				var result = await this.http("/api/sms",{phone:this.phone}).catch(err=>{
					console.log(err);
				})
					// console.log(result)
					uni.setStorageSync("code",result.data.list.code)
					
					//当发送验证码后，验证码不可再点击
					this.codeTag=false
					
					//倒计时
					this.second = 5
					
					var timer = setInterval(()=>{
						if(this.second<=0){
							clearInterval(timer);
							this.second="";
							this.codeTag=true
							return
						}
						this.second-=1
					},1000)
							
			},
			async login(){
				var codes = uni.getStorageSync("code")
				if(codes == this.code){
					var result = await this.http("/api/wxlogin",{phone:this.phone}).catch(err=>{
						console.log(err);
					})
					// console.log(result);
					uni.setStorageSync("userInfo",result.data.list)
					
					uni.reLaunch({
						url:"/pages/mine/mine"
					})
				}
			}
		}
		
	}
</script>

<style>
	/* 导入外部的样式文件 */
	/* @import url("../../common/css/index.css"); */
	.box{
		position: relative;
	}

	.row{
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		margin: 40rpx;
	}
	.send{
		display: flex;
		justify-content: space-between;
	}
	.send text:nth-of-type(2){
		color: #00BB00;
	}
	text{
		font-size: 27rpx;
		margin-bottom: 10rpx;
	}
	input{
		border-bottom: 1rpx solid gray;
		height: 65rpx;
	}
	.captcha{
		margin-left: 0rpx;
	}
	
</style>
